package com.zzyl.intercept;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.zzyl.constant.CacheConstant;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {
    @Autowired
    JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //专门用来比较请求路径的
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断请求是否是后端请求 如果不是则直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //2.从请求头中获取token 判断token是否为空 为空返回401
        String token = request.getHeader(Constants.USER_TOKEN);
        if(ObjectUtil.isEmpty(token)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //3.解析token 然后判断数据是否为空 如果为空则返回401
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        String json = String.valueOf(claims.get("currentUser"));
        UserVo userVo = JSONUtil.toBean(json, UserVo.class);

        //4.构建redis的key 然后从redis中获取到当前用户的权限列表
        String key = CacheConstant.PUBLIC_ACCESS_URLS + userVo.getId();
        String jsonList = stringRedisTemplate.opsForValue().get(key);
        List<String> urlList = JSONUtil.toList(jsonList, String.class);

        //5.获取当前请求的地址和请求方式
        String path = request.getMethod() + request.getRequestURI();

        //6.判断当前的请求地址是否在权限列表中 如果不在返回403
        Boolean flag = Boolean.FALSE;
        for (String url : urlList) {
            if(antPathMatcher.match(url,path)){
                flag = Boolean.TRUE;
                break;
            }
        }
        //7.把用户id存储到ThreadLocal中 然后放行
        if (flag){
            UserThreadLocal.set(userVo.getId());
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }
}
